<?php
// table_edit.php
// SuperConstructor Table Editor
// Edits an existing table in the database
// Copyright 2007, Alex McClung
// TODO: Make sure nobody tries to create a table whose name starts with 'sc_'
require_once("../lib/func.autoloader.php");

// If the user is not logged in, redirect them to the login page
$sc = new SuperConstructor();
if(false === $sc->getUser()) { header("Location: {$sc->config->LoginPage}"); exit(); }

// Has POST data been submitted?
if(count($_POST) > 0)
{
/*
	// Load post data
	foreach($_POST as $varname=>$value)
	{
		// Ignore everything that begins with an underscore (because it's used by the system)
		if(substr($varname, 0, 1) == "_")
			continue;
			
		// Look in the $_POST['_required'] array, if _colname is in there, it's required
		// So check to make sure it's not empty
		if(array_search($varname, $_POST['_required']) !== false && $value == "")
			MQ::Push("<strong>$varname</strong> is required.", MQ_ERROR);
		else
		{
			// Capture the variable for ourselves, AND give it to the template
			$$varname = $value;
			$sc->assign($varname, $value);
		}
	}
	
	// If there are no error messages, we can try and create the table
	if( MQ::NumMessages(MQ_ERROR) == 0 )
	{
		// Create a new table object, fill in simple POST data
		$t          = new SimpleTable();
		$t->name    = $tablename;
		$t->comment = $comments;
		
		// Loop through the columns, add 'em to the table
		for($i=0; $i < $num_columns; $i++)
		{
			// First idiot check: make sure the column has a NAME
			if(strlen($colnames[$i]) == 0)
			{
				MQ::Push("Column $i's name is empty", MQ_ERROR);
				continue;
			}
			
			// Create the column, fill in its data, stick it in the table
			$c                 = new SimpleColumn();
			$c->name           = $colnames[$i];
			$c->type           = $coltypes[$i];
			$c->fieldinfo      = $collengths[$i];
			$c->attributes     = $colattribs[$i];
			$c->null           = $colnulls[$i];
			$c->default        = $coldefaults[$i];
			$c->fulltext       = isset($colfulltexts[$i]);
			$c->auto_increment = isset($colincrements[$i]);
			$c->primary_key    = ($colkeys[$i] == "PRIMARY"); // TODO: Replace this with a constant!
			$c->unique         = ($colkeys[$i] == "UNIQUE" ); // TODO: Replace this with a constant!
			$c->index          = ($colkeys[$i] == "INDEX"  ); // TODO: Replace this with a constant!
			$t->AddColumn($c);
		}
		
		// Are there STILL no messages?
		if( MQ::NumMessages(MQ_ERROR) == 0 )
		{
			// Create the table
			if($t->Create())
			{
				// TODO: Supply a better success message
				MQ::Push("Created the table!", MQ_OK);
				
				// TODO: Clear form data
			}
			else
			{
				// TODO: Supply a better failure message
				MQ::Push("Error creating table.", MQ_ERROR);
				MQ::Push($t->LastError(), MQ_ERROR);
			}
		}
	}
*/
}
// No POST data hase been submitted. Get the table info from the table
// specified in GET
else
{
	// Have the SimpleTable do all the hard work
	$name = $_GET['table'];
	$t = new SimpleTable($name);
	
	// Make some nasty arrays for the form to use
	$comments = $key = "";
	$colnames = $coltypes = $collengths = $colattribs = $colnulls = $coldefaults = $colkeys = $colfulltexts = $colincrements = array();
	
	foreach($t->columns as $column)
	{
			 if( $column->primary_key ) { $key = "PRIMARY"; }
		else if( $column->unique      ) { $key = "UNIQUE";	}
		else if( $column->index       ) { $key = "INDEX";	}
		else							{ $key = "";		}
		
		$colnames[]      = $column->name;
		$coltypes[]      = strtoupper($column->type);
		$collengths[]    = strtoupper($column->fieldinfo);
		$colattribs[]    = strtoupper($column->attributes);
		$colnulls[]      = strtoupper($column->null);
		$coldefaults[]   = $column->default;
		$colkeys[]       = $key;
		$colfulltexts[]  = $column->fulltext;
		$colincrements[] = $column->auto_increment;
	}
	
	// Get the default form variables in there
	$sc->assign("num_columns",          count($t->columns) );
	$sc->assign_by_ref("tablename",     $t->name           );
	$sc->assign_by_ref("comments",      $t->comments       );
	$sc->assign_by_ref("colnames",      $colnames          );
	$sc->assign_by_ref("coltypes",      $coltypes          );
	$sc->assign_by_ref("collengths",    $collengths        );
	$sc->assign_by_ref("colattribs",    $colattribs        );
	$sc->assign_by_ref("colnulls",      $colnulls          );
	$sc->assign_by_ref("coldefaults",   $coldefaults       );
	$sc->assign_by_ref("colkeys",       $colkeys           );
	$sc->assign_by_ref("colfulltexts",  $colfulltexts      );
	$sc->assign_by_ref("colincrements", $colincrements     );
	
	// Cleanup
	unset($t, $column, $key, $name);
}

// Assign template vars
$sc->assign("pageTitle",       "Edit a Table");
$sc->assign("extraStyles",     array("common/css/te.css") );
$sc->assign("extraScripts",    array("common/js/te.js")   );

// TODO: Define these as constants somewhere (or properties of the Column class?)
$sc->assign("_column_types",   array("BIGINT","BINARY","BLOB","BOOL","CHAR","DATE","DATETIME","DECIMAL","DOUBLE","ENUM","FLOAT","INT","LONGBLOB","LONGTEXT","MEDIUMBLOB","MEDIUMINT","MEDIUMTEXT","SET","SMALLINT","TEXT","TIME","TIMESTAMP","TINYBLOB","TINYINT","TINYTEXT","VARCHAR","VARBINARY","YEAR"));
$sc->assign("_column_attribs", array("","UNSIGNED","UNZIGNED ZEROFILL"=>"UNSIGNED ZEROFILL","ON UPDATE CURRENT_TIMESTAMP"=>"UPDATE TIMESTAMP") );
$sc->assign("_column_nulls",   array("NOT NULL", "NULL")  );
$sc->assign("_column_keys",    array("", "PRIMARY", "INDEX", "UNIQUE") );

// Display the template
$sc->display("admin/pages/table_editor/edit.tpl");
?>